package cn.btks.backstagemanage.role.service.impl;

import cn.btks.backstagemanage.menu.dto.MenuDto;
import cn.btks.backstagemanage.menu.pojo.Menu;
import cn.btks.backstagemanage.menu.service.MenuService;
import cn.btks.backstagemanage.role.dto.RoleDto;
import cn.btks.backstagemanage.role.pojo.Role;
import cn.btks.backstagemanage.role.repository.RoleBaseRepository;
import cn.btks.backstagemanage.role.repository.RoleRepository;
import cn.btks.backstagemanage.role.service.RoleService;
import cn.btks.backstagemanage.user.pojo.User;
import cn.btks.commonserver.pojo.PageList;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.sm2.SM2EncDecUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2021/1/7 11:29
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    MenuService menuService;

    @Autowired
    RoleBaseRepository roleBaseRepository;

    @Override
    public Role findById(Long id) {
        Optional<Role> optional = roleRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<RoleDto> findAll() {
        List<RoleDto> roleDtoList = new ArrayList<>();
        List<Role> roleList = roleRepository.findAll();
        if(roleList != null && roleList.size() > 0){
            for (Role role : roleList){
                RoleDto roleDto = new RoleDto();
                roleDto.setRole(role);
                List<MenuDto> menuDtoList = menuService.findByRoleId(role.getId());
                roleDto.setMenuDtoList(menuDtoList);
                roleDtoList.add(roleDto);
            }
        }
        return roleDtoList;
    }

    @Override
    public List<RoleDto> findAll2() throws IOException {
        List<RoleDto> roleDtoList = new ArrayList<>();
        List<Role> roleList = roleRepository.findAll();
        if(roleList != null && roleList.size() > 0){
            for (Role role : roleList){
                RoleDto roleDto = new RoleDto();
                roleDto.setRole(role);
                List<MenuDto> menuDtoList = menuService.findByRoleId1(role.getId());
                roleDto.setMenuDtoList(menuDtoList);
                roleDtoList.add(roleDto);
            }
        }
        return roleDtoList;
    }

    @Override
    public List<Role> findAll1() {
        return roleRepository.findAll();
    }

    @Override
    public List<Role> findAllByIsCity(Integer isCity) {
        return roleRepository.findAllByIsCity(isCity);
    }

    @Override
    public ResultState findPageList(Integer page, Integer pageSize, String roleName) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Specification<Role> specification = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(roleName)) {
                    predicates.add(criteriaBuilder.like(root.get("roleName"),
                            "%" + roleName + "%"));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<Role> configPage = roleRepository.findAll(specification, pageRequest);
        if(configPage.getTotalElements() > 0){
            List<RoleDto> roleDtoList = new ArrayList<>();
            List<Role> content = configPage.getContent();
            if(content != null && content.size() > 0){
                for (Role role : content){
                    RoleDto roleDto = new RoleDto();
                    roleDto.setRole(role);
                    List<MenuDto> menuDtoList = menuService.findByRoleId(role.getId());
                    roleDto.setMenuDtoList(menuDtoList);
                    roleDtoList.add(roleDto);
                }
            }
            PageList pageList = new PageList();
            pageList.setResult(roleDtoList);
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState findPageList1(Integer page, Integer pageSize, String roleName) throws IOException {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Specification<Role> specification = new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(roleName)) {
                    predicates.add(criteriaBuilder.like(root.get("roleName"),
                            "%" + roleName + "%"));
                }
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<Role> configPage = roleRepository.findAll(specification, pageRequest);
        if(configPage.getTotalElements() > 0){
            List<RoleDto> roleDtoList = new ArrayList<>();
            List<Role> content = configPage.getContent();
            if(content != null && content.size() > 0){
                for (Role role : content){
                    RoleDto roleDto = new RoleDto();
                    roleDto.setRole(role);
                    List<MenuDto> menuDtoList = menuService.findByRoleId1(role.getId());
                    roleDto.setMenuDtoList(menuDtoList);
                    roleDtoList.add(roleDto);
                }
            }
            PageList pageList = new PageList();
            pageList.setResult(roleDtoList);
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState save(Role role) {
        Role role2 = roleRepository.findByRoleCode(role.getRoleCode());
        if(role2 != null){
            return new ResultState(StateInfo.SAVE_ERROR3.getCode(), StateInfo.SAVE_ERROR3.getMsg());
        }
        String roleCode = "ROLE_"+role.getRoleCode();
        role.setRoleCode(roleCode);
        Role role1 = roleRepository.save(role);
        return role1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), role1) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(Role role) {
        if(role.getId() != null){
            Optional<Role> optional = roleRepository.findById(role.getId());
            if(optional.isPresent()){
                Role role1 = roleRepository.save(role);
                return role1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), role1) :
                        new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState delete(Long id) {
        int userRolesCount = roleRepository.queryUserRolesCountByRoleId(id);
        int menuRolesCount = roleRepository.queryMenuRolesCountByRoleId(id);
        if(userRolesCount > 0 || menuRolesCount > 0){
            return new ResultState(StateInfo.DELETE_ERROR_3.getCode(), StateInfo.DELETE_ERROR_3.getMsg());
        }else {
            int result = roleRepository.deleteRoleById(id);
            return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg(), result):
                    new ResultState(StateInfo.DELETE_ERROR.getCode(), StateInfo.DELETE_ERROR.getMsg());
        }
    }

    @Override
    public ResultState delete1(Long id) throws IOException {
        int userRolesCount = roleRepository.queryUserRolesCountByRoleId(id);
        int menuRolesCount = roleRepository.queryMenuRolesCountByRoleId1(SM2EncDecUtils.encrypt(String.valueOf(id)));
        if(userRolesCount > 0 || menuRolesCount > 0){
            return new ResultState(StateInfo.DELETE_ERROR_3.getCode(), StateInfo.DELETE_ERROR_3.getMsg());
        }else {
            int result = roleRepository.deleteRoleById(id);
            return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg(), result):
                    new ResultState(StateInfo.DELETE_ERROR.getCode(), StateInfo.DELETE_ERROR.getMsg());
        }
    }

    @Override
    public ResultState deleteConnectionByMenuId(Long roleId,Long menuId) {
        List<Long> menuIdList = new ArrayList<>();
        Menu menu = menuService.findById(menuId);
        if(menu != null){
            menuIdList.addAll(recursion(menuId,roleId));
        }
        if(menuIdList.size() > 0){
//            for(Long id : menuIdList){
//                int result = roleRepository.deleteConnectionByRoleIdAndMenuId(roleId, id);
//            }
            roleBaseRepository.deleteMenuRoles(roleId,menuIdList);
        }
        return new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg());
    }

    @Override
    public ResultState deleteConnectionByMenuId1(Long roleId, Long menuId) throws IOException {
        List<Long> menuIdList = new ArrayList<>();
        Menu menu = menuService.findById(menuId);
        if(menu != null){
            menuIdList.addAll(recursion1(menuId,roleId));
        }
        if(menuIdList.size() > 0){
            roleBaseRepository.deleteMenuRoles1(roleId,menuIdList);
        }
        return new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg());
    }

    /**
     * 递归
     * @param menuId
     * @return
     */
    private List<Long> recursion(Long menuId,Long roleId) {
        List<Long> menuIdList = new ArrayList<>();
        int result = roleRepository.queryMenuRolesCountByMenuIdAndRolesId(menuId,roleId);
        if(result > 0){
            menuIdList.add(menuId);
        }
        List<Menu> menuList = menuService.findAllByParentId(menuId);
        if (menuList != null && menuList.size() > 0) {
            for (Menu item : menuList) {
                List<Long> menuIdListTemp = recursion(item.getId(),roleId);
                menuIdList.addAll(menuIdListTemp);
            }
        }
        return menuIdList;
    }

    /**
     * 递归
     * @param menuId
     * @return
     */
    private List<Long> recursion1(Long menuId,Long roleId) throws IOException {
        List<Long> menuIdList = new ArrayList<>();
        int result = roleRepository.queryMenuRolesCountByMenuIdAndRolesId1(SM2EncDecUtils.encrypt(String.valueOf(menuId)),SM2EncDecUtils.encrypt(String.valueOf(roleId)));
        if(result > 0){
            menuIdList.add(menuId);
        }
        List<Menu> menuList = menuService.findAllByParentId(menuId);
        if (menuList != null && menuList.size() > 0) {
            for (Menu item : menuList) {
                List<Long> menuIdListTemp = recursion(item.getId(),roleId);
                menuIdList.addAll(menuIdListTemp);
            }
        }
        return menuIdList;
    }
}
